import { asyncRoutes, staticRoutes } from '@/routes';
import { IRoute } from '@/types/router';
import { UserMenuRes } from '@/types/user';

/**
 * 递归permissions，赋予当前route是否存在权限
 * @param permissions
 * @param route
 */
function getRouterPermission(route: IRoute, permissions: UserMenuRes[]) {
  for (let i = 0, len = permissions.length; i < len; i++) {
    if (route.authCode === permissions[i].authCode) {
      if (Number(permissions[i].authFlag) === 1) {
        return true;
      }
    } else if (permissions[i].children && permissions[i].type < 2) {
      const childPermissions = permissions[i].children || [];
      const nextFlag = getRouterPermission(route, childPermissions);
      if (nextFlag) return true;
    }
  }
  return false;
}

/**
 * 根据permissions，判断当前route是否存在权限
 * @param permissions
 * @param route
 */
function hasPermission(route: IRoute, permissions: UserMenuRes[]) {
  if (route.authCode) {
    const flag = getRouterPermission(route, permissions);
    return flag;
  }
  return true;
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param permissions
 */
function filterAsyncRouter(routes: IRoute[], permissions: UserMenuRes[]) {
  const accessedRouters = routes.filter((route) => {
    if (hasPermission(route, permissions)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissions);
      }
      return true;
    }
    return false;
  });
  return accessedRouters;
}

function generalAccessRoutes(permissions: UserMenuRes[]) {
  const nowRoutes = filterAsyncRouter(asyncRoutes, permissions);
  return staticRoutes.concat(nowRoutes);
}

export default generalAccessRoutes;
